//
//  ShoppingCartViewController.m
//  wtshoppingcite
//
//  Created by TW on 14-11-11.
//  Copyright (c) 2014年 TW. All rights reserved.
//

#import "ShoppingCartViewController.h"
#import "NetServiseCommonData.h"
#import "BaseTableView.h"
#import "ShoppingCartCell.h"
#import "ShoppingCartModel.h"
#import "ShoppingCartTableView.h"
#import "JVButton.h"
#import "RegisterHelper.h"
#import "SubmitViewController.h"

@interface ShoppingCartViewController ()<UITableViewEventsDelegate>
{
    UIButton *totalButton;
}
@property(retain,nonatomic)ShoppingCartTableView *shoppingCartTableView;

@end

@implementation ShoppingCartViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    _shoppingCartArray = [[NSMutableArray alloc]initWithCapacity:1];
    
    [self setTitleView:@"购物车"];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self getShoppingCartData];
    
    [self initWithView];
    
    [self setRightButton:@"编辑" sel:@selector(editButtonAction) viewController:self];
    
    self.isSelect = 0;
    // Do any additional setup after loading the view.
}



-(void)initWithView{
    
    _shoppingCartTableView = [[ShoppingCartTableView alloc]initWithFrame:CGRectMake(0, 0, kWidth, kHeight-60) style:UITableViewStylePlain];
    _shoppingCartTableView.data = _shoppingCartArray;
    [self.view addSubview:_shoppingCartTableView];
    
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, kHeight-60, kWidth, 60)];
    view.backgroundColor = [UIColor clearColor];
    [self.view addSubview:view];
    
    UIView *seperateView = [[UIView alloc]initWithFrame:CGRectMake(0, 2, kWidth, 1)];
    seperateView.backgroundColor = UIColorFromRGB(0x95a0a0);
    [view addSubview:seperateView];
    
    UIButton  *chooseButton = [[UIButton alloc]initWithFrame:CGRectMake(10, 20, 80, 30)];
    chooseButton.tag = 10000;
    [chooseButton setTitle:@"全选" forState:UIControlStateNormal];
    [chooseButton setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
    [chooseButton setFont:[UIFont systemFontOfSize:15]];
    [view addSubview:chooseButton];
    [chooseButton addTarget:self action:@selector(chooseButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [chooseButton setTitleColor: UIColorFromRGB(0x9fa0a0) forState:UIControlStateNormal];
    
    
    totalButton = [[UIButton alloc]initWithFrame:CGRectMake(5, 10, 80, 40)];
    totalButton.right = kWidth -10;
    [totalButton setTitle:@"结算" forState:UIControlStateNormal];
    [totalButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [totalButton setBackgroundColor:MAIN_BLUE_COLOR];
    [totalButton addTarget:self action:@selector(totalAction:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:totalButton];
    
}

#pragma mark 全选
-(void)chooseButtonAction:(UIButton *)btn{
 
    if(self.isSelect == 1){
    [btn setImage:[UIImage imageNamed:@"choose_select_org.png"] forState:UIControlStateNormal];
    _shoppingCartTableView.allSelect = YES;
    [_shoppingCartTableView reloadData];
        self.isSelect = 0;
    }else if (self.isSelect==0){
        [btn setImage:[UIImage imageNamed:@"choose"] forState:UIControlStateNormal];
        _shoppingCartTableView.allSelect = NO;
        [_shoppingCartTableView reloadData];
        self.isSelect = 1;
    }
}

#pragma mark 编辑按钮
-(void)editButtonAction{
    _shoppingCartTableView.isEdit = YES;
    [_shoppingCartTableView reloadData];
    
    [totalButton setTitle:@"删除" forState:UIControlStateNormal];
    [totalButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [totalButton setBackgroundColor:[UIColor grayColor]];
    [totalButton setBackgroundColor:MAIN_BLUE_COLOR];
    [self setRightButton:@"完成" sel:@selector(finishAction) viewController:self];
}

#pragma mark finishAction
-(void)finishAction{
    
    _shoppingCartTableView.isEdit = NO;
    [_shoppingCartTableView reloadData];
    
    [self setRightButton:@"编辑" sel:@selector(editButtonAction) viewController:self];
    [totalButton setTitle:@"结算" forState:UIControlStateNormal];
    [totalButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [totalButton setBackgroundColor:MAIN_BLUE_COLOR];
}

#pragma mark 获取购物车商品列表
-(void)getShoppingCartData{
    
    
    NSArray *array = [[RegisterHelper shareHelper]purchaseArray];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    SetValueForKey(param, array, @"productIds");
    //SetValueForKey(param, productIds, @"productIds");
    
    [NetWorkService byRequestWithAPIPrefix:kBaseAppUrl
                              andAPISuffix:kPurchase
                             andHttpMethod:@"POST"
                             andParameters:param
                           andRequestCache:NO
                            andUseParamDic:YES
                       andPostDataEncoding:MKNKPostDataEncodingTypeJSON
                     andRequestFinishBlock:^(BYRequest *request, BYResponse *response) {
                         
                         
                         if (response.isError) {
                             DLog(@"error %@",response.errorMessage);
                         }else{
                             NSDictionary *responseDic = request.responseJSON;
                             DLog(@"成功数据:%@",responseDic);
                             
                             NSArray *list = [responseDic objectForKey:@"list"];
                             
                             for (NSDictionary *dic in list) {
                                 ShoppingCartModel *shoppingModel = [[ShoppingCartModel alloc]initWithShoppingCartInfo:dic];
                                 [_shoppingCartArray addObject:shoppingModel];
                             }
                             _shoppingCartTableView.data = _shoppingCartArray;
                             //_shoppingCartTableView.isEdit = NO;
                         }
                         [_shoppingCartTableView reloadData];
                     }];
    
}

#pragma mark totalAction 结算&删除
-(void)totalAction:(UIButton *)sender{
    
    
    
    if ([sender.titleLabel.text isEqual: @"结算"]) {
        NSLog(@"结算");
        
        
        for (int i = 0; i < _shoppingCartArray.count; i++) {
            
            ShoppingCartModel *shoppingCartModel = [_shoppingCartArray objectAtIndex:i];
            
            CGFloat oPrice = [shoppingCartModel.oPrice floatValue];
            NSInteger sum =  [[[RegisterHelper shareHelper].shopCarNumbers objectForKey:shoppingCartModel.sid] integerValue];
            _total = _total + oPrice * sum;
            //[RegisterHelper shareHelper].totalNum = _total;//合计
        }
        
        SubmitViewController *submitVC = [[SubmitViewController alloc]init];
        submitVC.hidesBottomBarWhenPushed = YES;
        submitVC.totalSum = _total;
        submitVC.dataArray = _shoppingCartArray;
        [self.navigationController pushViewController:submitVC animated:YES];
        
    }else{
        NSInteger count = [RegisterHelper shareHelper].deleteArray.count;
        
        for (int i = 0; i< count; i++) {
            ShoppingCartModel *shoppingCartModel = [[RegisterHelper shareHelper].deleteArray objectAtIndex:i];
           
            [_shoppingCartArray removeObject:shoppingCartModel];
            [[RegisterHelper shareHelper].purchaseArray removeObject:shoppingCartModel.sid];
        }
        [_shoppingCartTableView reloadData];
    }
    
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [_shoppingCartTableView reloadData];
    ;
}


- (void)viewWillDisappear:(BOOL)animated
{
    
    [super viewWillDisappear:animated];
     [_shoppingCartTableView reloadData];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
